package chapter02.part01;

import chapter02.FileUtil;

import java.io.*;
import java.nio.CharBuffer;

/**
 * 认识流家族的结构 P46
 * 整体可分为字节和字符
 * 
 * @author insight
 * @since 2021/8/5
 */
public class IOStreamFamily {
    public static void main(String[] args) throws IOException {
        /* 字节 InputStream & OutputStream 构成基础 */
        
        // 根据功能有不同的实现
        // FileInputStream 读取文件内容
        FileInputStream fileInputStream = FileUtil.getTestFileInputStreamInstance();
        // DataInputStream 读取所有的基本 Java 类型
        DataInputStream dataInputStream = new DataInputStream(fileInputStream);
        double v = dataInputStream.readDouble();
        dataInputStream.close();

        /* 字符 Reader & Writer 构成基础*/
        // 字节->字符
        InputStreamReader inputStreamReader =
                new InputStreamReader(fileInputStream);
        // 利用缓冲提高效率
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        // 读取一个 unicode 结尾返回-1
        int unicode = bufferedReader.read();
        
        /* 4个附加接口 Closeable Flushable Readable Appendable 
        
        |------------| Closeable | Flushable | Readable | Appendable |
        |InputStream |     √     |           |          |            |
        |OutputStream|     √     |     √     |          |            |
        |   Reader   |     √     |           |    √     |            |
        |   Writer   |     √     |     √     |          |     √      |
        */
        
        // Closeable 扩展了 AutoCloseable
        // 所以可以使用 try-with-res
        // 之所以两个是因为 Closeable 抛出 IOException AutoCloseable 抛出 Exception
        try (final BufferedReader reader = new BufferedReader(inputStreamReader)) {
            reader.read();
        }
        
        // Readable 的方法 read(CharBuffer)
        // CharBuffer 可以按顺序或随机读写 表示缓冲区
        bufferedReader.read(CharBuffer.allocate(8));
        
        // Appendable 用于添加字符/字符序列
        // append(char) append(CharSequence)
        StringBuilder sb = new StringBuilder();
        sb.append('a');
        // CharSequence 描述一个字符序列的属性
        sb.append(new StringBuilder());
    }
}